package handler

import (
	"fmt"
	"golang-jwt/middleware"
	"golang-jwt/utils"
	"net/http"

	"github.com/gin-gonic/gin"
	"k8s.io/klog/v2"
)

func Login(ctx *gin.Context) {
	// 简单起见，直接把账号密码写在 url 的 query 参数里
	username := ctx.Query("username")
	password := ctx.Query("password")

	if username != "zhangsan" || password != "123456" {
		ctx.String(400, "账号或密码错误")
		return
	}

	tokenString, err := utils.GenerateJWT(username)
	if err != nil {
		ctx.String(400, fmt.Sprintf("生成 JWT 失败：%s", err.Error()))
		return
	}
	ctx.String(http.StatusOK, tokenString)
	klog.Infof("%s login!", username)
}

func ListApps(ctx *gin.Context) {
	udb := ctx.MustGet(middleware.UDB_KEY)

	apps := []string{}
	if udb == "zhangsan" {
		apps = append(apps,
			"zhangsan-app1",
			"zhangsan-app2",
		)
	}
	ctx.JSON(http.StatusOK, apps)
}
